package cn.qdhlm.testrocketmq.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Name:OrderedConsumer
 * @description:队列接受
 * @author: xinY
 **/
public class OrderedConsumer {
    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("example_group_name");
        // 设置从什么时候开始消费：last跳过历史，first不跳过历史，
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.setVipChannelEnabled(false);
        // 连接
        consumer.setNamesrvAddr("192.168.0.159:9876");
        // 订阅主题
        consumer.subscribe("TopicTest", "*");
        // 设置广播模式消费
//        consumer.setMessageModel(MessageModel.BROADCASTING);
//        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 注册监听接收消息
        consumer.registerMessageListener(new MessageListenerOrderly() {

            final AtomicLong consumeTimes = new AtomicLong(0);
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs,
                                                       ConsumeOrderlyContext context) {
                context.setAutoCommit(true);
                for (MessageExt msg : msgs) {
                    System.out.print(Thread.currentThread().getName() + "收到消息:");
                    System.out.println("topic:"+msg.getTopic()+", tags:"+msg.getTags()+", body:"+new String(msg.getBody()));
                }

                return ConsumeOrderlyStatus.SUCCESS;

            }
        });
        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}
